<div class="container">
  <input type="hidden" id="topic-id" value="<%= typeof(topicId) !== 'undefined' ? topicId : '' %>"/>
  <input type="hidden" id="zone-object" value="<%= typeof(zone) !== 'undefined' ? JSON.stringify(zone) : '' %>"/>
  <div class="col-md-4">
    <div class="panel panel-default">
      <div class="panel-heading">
        宣传图
        <div class="pull-right">
        <a v-on:click="onUploadImage">上传</a>
        •
        <a v-on:click="onDeleteImage"> 删除</a>
        </div>
      </div>
      <div class="panel-body">
          <a href="#" class="thumbnail" v-if="advertisingMap" v-cloak>
            <img v-bind:src="advertisingMap">
          </a>
          <p v-else>没有图</p>
      </div>
    </div>
  </div>
  <div class="col-md-8">
    <div class="panel panel-default">
      <div class="panel-heading">
        <div class="panel-title" v-if="pageTitle" v-cloak>{{ pageTitle }}</div>
      </div>
      <div class="panel-body">

        <div class="form-group">
          <label for='title'>职位名称</label>
          <input autofocus type="text" class="form-control" id='title' name='title' placeholder="职位名称" v-model="title">
        </div>

        <div class="form-group">
          <label for='area'>工作地点</label>
          <input autofocus type="text" class="form-control" id='area' name='area' placeholder="" v-model="area">
        </div>

        <div class="form-group">
          <label for='area'>标签</label>
          <ul id="topicTags">
          </ul>
        </div>

        <div class='markdown_editor in_editor'>
          <div class='markdown_in_editor'>
            <textarea class='form-control editor' name='t_content' rows='20' placeholder='支持 Markdown 语法'></textarea>
          </div>
        </div>
        <button class='btn btn-primary' v-on:click="onSave('reviewed')">保存</button>
        <% if(typeof(csrf) !== 'undefined') {%>
        <input type='hidden' name='_csrf' value='<%= csrf %>'>
        <% } %>
        <button type="button" class="btn btn-primary pull-right" v-on:click="onPreview">预览</button>
        <input type="checkbox" id="checkbox" v-model="isHtml">
        <label for="checkbox">html编辑模式</label>
      </div>
    </div>
  </div>
</div>
<!-- Modal -->
<div class="modal fade previewDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">预览</h4>
      </div>
      <div class="modal-body">
        <div id="preview-content" class='<%=config.mdType%>-body content preview-content'>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<!-- markdown editor -->
<%- partial('../../includes/editor') %>
<script>
  var appId = $('[name=app-id]').val();
  var zoneObjString = $('#zone-object').val();
  var zoneObj = zoneObjString ? JSON.parse(zoneObjString) : {};
  var sampleTags = [];

  $('#topicTags').tagit({
      availableTags: sampleTags,
      removeConfirmation: true,
      itemName: 'item',
      fieldName: 'tags'
  });
  var topicId = $('#topic-id').val();

  var pagePrefix = '<%= apiPrefix.page %>';
  var dataPrefix = '<%= apiPrefix.data %>';
  var submitUrl = dataPrefix + '/zone/' + zoneObj.key + '/' + zoneObj.template + '/topic/' + topicId + '/edit';

  var editor = new Editor();
  editor.render($('.editor')[0]);

  var vue = new Vue({
    el: '#app',
    data: {
      zoneObj: {},
      topicId: '',
      title: '',
      area: '',
      advertisingMap: '',
      pageTitle: '编辑',
      topic: '',
      isHtml: false,
      errorMsg: '',
      successMsg: ''
    },
    methods: {
      getTopic: function() {
        $.post(dataPrefix + '/topic/' + this.topicId + '/data',
        {
          appId: appId
        },
        function (result) {
          if (result.err) {
            vue.errorMsg = result.err;
          } else {
            vue.topic = result.data || {};
            vue.zoneObj._id = vue.topic.zoneId || '';
            vue.title = vue.topic.title || '';
            vue.area = vue.topic.area || '';
            vue.advertisingMap = vue.topic.advertisingMap || '';
            vue.tags = vue.topic.tags && vue.topic.tags !== '' ? vue.topic.tags.split(',') : [];
            vue.isHtml = vue.topic.isHtml;
            editor.codemirror.setValue(vue.topic.content || '');
            vue.getMenus();
            updateTags(vue.tags);
          }
        });
      },
      onSave: function(status) {
        vue.errorMsg = ''
        if (vue.title === '') {
          vue.errorMsg = '标题为空';
          return;
        }

        if (editor.codemirror.getValue() === '') {
          vue.errorMsg = '内容为空'
          return;
        }

        $.post(submitUrl,
          {
            appId: appId,
            _csrf: $('#_csrf').val(),
            zoneId: vue.zoneObj._id,
            title: vue.title,
            area: vue.area,
            advertisingMap: vue.advertisingMap,
            content: editor.codemirror.getValue(),
            tags: getTags(),
            isHtml: vue.isHtml,
            status: status? status : 'reviewed'
          },
          function (result) {
            if (result.err) {
              vue.errorMsg = result.err;
            } else {
              location.href = result.url;
            }
        });
      },
      onPreview: function() {
        var md = new markdownit()
        $('div#preview-content').empty()
        $('div#preview-content').append(md.render(editor.codemirror.getValue()))
        $('.previewDialog').modal('show')
      },
      onUploadImage: function() {
        var imageUpload = new ImageUpload();
        imageUpload.bind(uploadImageCallback);
      },
      onDeleteImage: function() {
        vue.advertisingMap = '';
      }
    }
  });

  function uploadImageCallback(url) {
    vue.advertisingMap = url;
  }

  function getTags() {
    var tags = [];
    $("input[name='tags']").each(function(index,item) {
      tags.push($(this).val())
    });

    return tags;
  }

  function updateTags(tags) {
    tags.forEach(item => {$("#topicTags").tagit("createTag", item)})
  }

  vue.topicId = topicId;
  vue.pageTitle = '编辑';
  vue.getTopic();
</script>
